package com.example.demo.service;

import com.example.demo.mapper.UserMapper;
import com.example.demo.model.entity.User;
import com.example.demo.model.request.LoginRequest;
import com.example.demo.utils.JwtTokenUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    /*private static String encryption(@NotNull String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            messageDigest.update(str.getBytes());
            return new BigInteger(messageDigest.digest()).toString(32);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }*/

    public Boolean updateAuthorization(HttpServletResponse servletResponse, User user) {
        String token = JwtTokenUtil.generateAuthorization(user);
        servletResponse.setHeader("Authorization",token);
        return true;
    }
    
    public User findUserByUserName(LoginRequest request){
        User user = userMapper.findUserByUserName(request.getUserName());
        return user;
    }

    public User userJudge(HttpServletRequest servletRequest){
        return JwtTokenUtil.getUserByToken(servletRequest);
    }

    public void deleteUserToken(HttpServletResponse servletResponse) {
        servletResponse.setHeader("Authorization", null);
    }

    public void register(LoginRequest request) {
        User user = new User();
        user.register(request.getUserName(), request.getPassWord());
        userMapper.register(user);
    }

}
